package com.action.boot.jpa.controller;

import com.action.boot.jpa.repository.TestInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

/**
 * Created by Wuxiang on 2017/3/25.
 */
@Controller
public class IndexController {

    @RequestMapping(value = "/",method = RequestMethod.GET)
    @ResponseBody
    public String home() {
        //返回数据
        return "Quick start!";
    }

    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public String toIndex() {
        //返回页面
        return "index";
    }

    //Model 包含四个addAttribute 和一个  merAttribute方法的接口
    //向页面返回处理数据
    @RequestMapping(value = "/testModel",method = RequestMethod.GET)
    public String greeting(Model model) {
        model.addAttribute("name", "Quick start!");
        model.addAttribute("age", 18);
        return "testModel";
    }

    //ModelMap 向页面返回处理数据
    @RequestMapping(value = "/testModelMap",method = RequestMethod.GET)
    public String test(ModelMap modelMap) {
        TestInfo infoA = new TestInfo();
        infoA.setId((long) 1);
        infoA.setName("Bob");
        infoA.setBirth(new Date());
        TestInfo infoB = new TestInfo();
        infoB.setId((long) 2);
        infoB.setName("Tom");
        infoB.setBirth(new Date());

        modelMap.addAttribute("a", infoA);
        modelMap.put("b", infoB);   //ModelMap 实现了map接口，包含map的方法
        return "testModelMap";
    }

    //ModelAndView 两个作用   1.向页面返回处理数据   2.设置转向地址
    //ModelAndView多用在 @RestController中，即含有@ResponseBody注解
    @RequestMapping(value = "/testModelAndView", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView testMAV() {
        TestInfo infoA = new TestInfo();
        infoA.setId((long) 3);
        infoA.setName("Lady");
        infoA.setBirth(new Date());
        TestInfo infoB = new TestInfo();
        infoB.setId((long) 4);
        infoB.setName("Sim");
        infoB.setBirth(new Date());

        ModelAndView view = new ModelAndView("testModelMap");
        view.addObject("a", infoA);
        view.addObject("b", infoB);
        return view;
    }

}
